package com.cmy.framework_base.activity

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.os.SystemClock
import android.text.TextUtils
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import java.lang.ref.WeakReference

class ActivityContext : Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver {

    private val mActivityStack =  mutableListOf<WeakReference<Activity>>()

    private val mLifecycleListeners= mutableListOf<LifecycleListener>()

    private var mCurrentActivityReference: WeakReference<Activity>? = null

    private var mIsInBackground = true

//    private var hasMainActivity: Boolean = false

    //最后一次切到后台的时间
    private var mLastBackgroundTimeStamp: Long = 0

    companion object{
        private val sActivityContext = ActivityContext()
        fun getInstance(): ActivityContext {
            return sActivityContext
        }
    }

    fun registerLifecycleListener(lifecycleListener: LifecycleListener) {
       mLifecycleListeners.add(lifecycleListener)
    }

    fun unRegisterLifecycleListener(lifecycleListener: LifecycleListener) {
       mLifecycleListeners.remove(lifecycleListener)
    }

    @Synchronized
    fun getCurrentActivity(): Activity? {
        for (i in mActivityStack.indices.reversed()) {
            val weakReference: WeakReference<Activity> = mActivityStack[i]
            if (weakReference.get() != null) {
                return weakReference.get()
            }
        }
        return if (mCurrentActivityReference == null) null else mCurrentActivityReference?.get()
    }


    fun getActivityStack(): List<WeakReference<Activity>?> {
        return mActivityStack
    }


    fun isAppOnForeground(): Boolean {
        return !mIsInBackground
    }


    /**
     * 结束所有Activity
     */
    fun popAllActivity() {
        if (mActivityStack.size == 0) {
            return
        }
        for (weak in mActivityStack) {
            if (weak.get() != null) {
                weak.get()!!.finish()
            }
        }
        mActivityStack.clear()
    }

    /**
     * 添加Activity到堆栈
     */
    fun pushActivity(activity: Activity) {
        mActivityStack.add(WeakReference(activity))
    }

    /**
     * 结束指定的Activity
     */
    fun popActivity(activity: Activity) {
        if ( mActivityStack.size == 0) {
            return
        }
        val it = mActivityStack.iterator()
        while (it.hasNext()) {
            val weak = it.next()
            if (weak.get() != null && weak.get() === activity) {
                it.remove()
            }
        }
        if (!activity.isFinishing) {
            activity.finish()
        }
    }

    /**
     * 是否有指定类名的Activity
     */
    fun hasActivity(cls: Class<*>): Boolean {
        val it: Iterator<WeakReference<Activity>> = mActivityStack.iterator()
        while (it.hasNext()) {
            val weak = it.next()
            if (weak.get()!!.javaClass == cls) {
                return true
            }
        }
        return false
    }


    fun popActivity(cls: Class<*>) {
        val it = mActivityStack.iterator()
        while (it.hasNext()) {
            val weak = it.next()
            if (weak.get()!!.javaClass == cls) {
                if (!weak.get()!!.isFinishing) {
                    weak.get()!!.finish()
                }
                it.remove()
            }
        }
    }


    /**
     * 结束某个activity之上的所有activity
     */
    fun popAllActivityAboveOne(cls: Class<*>) {
        if (mActivityStack.size == 0) {
            return
        }
        var hasThisActivity = false
        for (weak in mActivityStack) {
            if (weak.get() != null) {
                if (cls == weak.get()!!.javaClass) {
                    hasThisActivity = true
                }
            }
        }
        if (!hasThisActivity) {
            return
        }
        val it = mActivityStack.iterator()
        var hasFindActivity = false
        while (it.hasNext()) {
            val weak = it.next()
            if (hasFindActivity && weak != null) {
//        popActivity(weak.get());
                val activity = weak.get()
                it.remove()
                if (!activity!!.isFinishing) {
                    weak.get()!!.finish()
                }
            }
            if (weak.get() != null && weak.get()!!.javaClass == cls) {
                hasFindActivity = true
            }
        }
    }


    /**
     * 获取指定的Activity
     *
     * @author kymjs
     */
    fun getSpecifiedActivity(cls: Class<*>?): Activity? {
        for (weakReference in mActivityStack) {
            if (weakReference.get() == null) {
                continue
            }
            val activity = weakReference.get()
            if (cls == activity!!.javaClass) {
                return activity
            }
        }
        return null
    }


    @Synchronized
    private fun checkAndCreateActivityReference(activity: Activity) {
        if (mCurrentActivityReference == null || mCurrentActivityReference?.get() !== activity) {
            mCurrentActivityReference = WeakReference(activity)
        }
        for (weakReference in mActivityStack) {
            if (weakReference.get() === activity) {
                return
            }
        }
        mActivityStack.add(WeakReference(activity))
    }


    @Synchronized
    private fun removeActivityReference(activity: Activity?) {
        if (activity == null) {
            return
        }
        val iterator: MutableIterator<WeakReference<Activity>> = mActivityStack.iterator()
        while (iterator.hasNext()) {
            val weakReference = iterator.next()
            if (weakReference != null) {
                val currentActivity = weakReference.get()
                if (currentActivity === activity || currentActivity == null) {
                    iterator.remove()
                }
            }
        }
    }


    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

        checkAndCreateActivityReference(activity)
        for (lifecycleListener in mLifecycleListeners) {
            lifecycleListener.onActivityCreate(activity, savedInstanceState)
        }
    }

    override fun onActivityStarted(activity: Activity) {
        //TODO onActivityStarted不应该设置当前页面，当有透明主题时Start只表示用户可见，不一定是当前页面。

    }

    override fun onActivityResumed(activity: Activity) {
        for (lifecycleListener in mLifecycleListeners) {
            lifecycleListener.onActivityResume(activity)
        }
    }

    override fun onActivityPaused(activity: Activity) {
        for (lifecycleListener in mLifecycleListeners) {
            lifecycleListener.onActivityPause(activity)
        }
    }

    override fun onActivityStopped(activity: Activity) {
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        removeActivityReference(activity)

        for (lifecycleListener in mLifecycleListeners) {
            lifecycleListener.onActivityDestroy(activity)
        }
    }


    override fun onStart(owner: LifecycleOwner) {
        mIsInBackground = false
        for (lifecycleListener in mLifecycleListeners) {
            lifecycleListener.onForeground()
        }
    }


    override fun onStop(owner: LifecycleOwner) {
        mIsInBackground = true
        mLastBackgroundTimeStamp = SystemClock.elapsedRealtime()
        for (lifecycleListener in mLifecycleListeners) {
            lifecycleListener.onBackground()
        }
    }


}